package SpaceIT.pages.Admin;

import java.io.File;
import java.util.ArrayList;

import model.dao.AdminSanPhamDAO;
import model.dao.SanPhamDAO;
import model.pojo.AdminSanPhamPOJO;
import model.pojo.NhanVien;
import model.pojo.SanPhamKhac;

import org.apache.tapestry5.annotations.ApplicationState;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.Grid;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.BeanModelSource;

import SpaceIT.pages.Index;

public class DanhSachSanPham {
	
	@ApplicationState
    private NhanVien NV;
	public Object onActivate()
	{
		if(NV.isDangNhap()==false)
		{			
			//NV.setDangNhap(false);
			return Index.class;
		}
		return null;
	}
	@Property
	@Persist
	private String message;
	public String EmptyMessage(){
		message = "";
		return "";
	}
	
	private AdminSanPhamPOJO sp;
	
	 public AdminSanPhamPOJO getSp() {
		return sp;
	}
	public void setSp(AdminSanPhamPOJO sp) {
		this.sp = sp;
		rowNoWithCurrentPage++;
	}
	@Property  
	private int noOfRowsPerPage=15; 
	
	public ArrayList<AdminSanPhamPOJO> getDSSanPham()
	{
		ArrayList<AdminSanPhamPOJO> arr= AdminSanPhamDAO.LayDSSanPham();
		
		return arr;
	}	
	private int rowNoWithCurrentPage;  
	 @Component(id = "myGrid")  
	 private Grid grid;  
	 public int getRowNo() {  
        int page = grid.getCurrentPage();  
        int rowNo = (page - 1) * noOfRowsPerPage + rowNoWithCurrentPage;  
  
        return rowNo;  
    }  
	 public String getMyRowClass() {  
        return (getRowNo() % 2 == 0 ? "even" : "odd");  
    }  
	@OnEvent(component="Xoa")
	void Xoa(String str)
	{
		try
		{
			
			  String Hinh = SanPhamDAO.LayHinhAnh(str);
			  String Path = this.getClass().getResource("./../../../").toURI().getRawPath();
			  Path = Path.substring(0,Path.lastIndexOf("/") - 1);
			  Path = Path.substring(0,Path.lastIndexOf("/") -1);
			  Path = Path.substring(0,Path.lastIndexOf("/"));
			  Path += "/src/main/webapp/";      		  
			 
			  

			  //System.out.print(sp.getHinhAnh());
		      File copied = new File(Path +Hinh);
		      if(copied.exists()){
		    	  boolean kqXoa = copied.delete();
		    	  if(kqXoa==true)
		    	  {
		    		  	String ma = str;
			  			boolean kq = SanPhamDAO.deleteSanPham(ma);
			  			if(kq == true)
			  			{
			  				message="Xóa Sản Phẩm Thành Công";
			  			}
			  			else
			  				message="Xóa Sản Phẩm Thất bại Do Xóa Hình Ảnh";
		    	  }
		    	  else
		    		  message="Xóa Sản Phẩm Thất bại";
		      }
			//message=str;
			
			//System.out.print(str);
		}
		catch (Exception e) {
			// TODO: handle exception
			message="Xóa Sản Phẩm Thất bại";
		}
	}
  
}
